<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import resconfig from '@/api/userService';
import appStore from '@/store';
import regions from '@/tips/regions.json';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import _ from 'lodash';
import mitt from '@/utils/mitt';
import userService from '@/api/userService';
import { encryptedData } from '@/api/crypto';
const router = useRouter();
const regionData: { [key: string]: string } = reactive(regions);
interface optionList {
  value: string;
  label: string;
}
const regionOptions: optionList[] = reactive([]);
let insertData = ref({} as { [key: string]: string });
let irData = reactive({
  data: {
    domain_name: '',
    project_id: '',
    access_key: '',
    secret_access_key: '',
    region: '',
    user_id: '',
    keypair_name: '',
    agency_name: '',
    auxproxy_path: '',
    build_script_path: '',
    file_storage_region: '',
    docker_build_script_path: '',
  },
} as { [key: string]: { [key: string]: string } });
const autoScalingRef = ref<FormInstance>();
const getRegion = async () => {
  let res = await userService.getRegion();
  let regionArr = res.data.regions;
  if (regionArr.length) {
    regionArr.forEach((element: any, index: any) => {
      regionOptions.push({
        value: regionArr[index],
        label: regionData[element],
      });
    });
  }
};
const rules = reactive<FormRules>({
  domain_name: [{ required: true, message: '请输入租户名称', trigger: 'blur' }],
  project_id: [{ required: true, message: '请输入项目id', trigger: 'blur' }],
  access_key: [{ required: true, message: '请输入Accesskey', trigger: 'blur' }],
  secret_access_key: [
    { required: true, message: '请输入SecretAccessKey', trigger: 'blur' },
  ],
  region: [{ required: true, message: '请选择Region', trigger: 'blur' }],
  keypair_name: [{ required: true, message: '请输入密钥名', trigger: 'blur' }],
});

const param = reactive({
  resconfig: {
    domain_name: '',
    project_id: '',
    access_key: '',
    secret_access_key: '',
    region: '',
    user_id: '',
    keypair_name: '',
    agency_name: '',
    auxproxy_path: '',
    build_script_path: '',
    file_storage_region: '',
    docker_build_script_path: '',
  },
});
let creating = ref(false);
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (creating.value) return;
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      param.resconfig = JSON.parse(JSON.stringify(irData.data));
      param.resconfig['user_id'] = insertData.value.id;
      param.resconfig.access_key = encryptedData(param.resconfig.access_key);
      param.resconfig.secret_access_key = encryptedData(
        param.resconfig.secret_access_key
      );
      try {
        creating.value = true;
        let res = await resconfig.createResconfig(param);
        if (res.status === 201) {
          creating.value = false;
          ElMessage({
            message: '创建成功',
            type: 'success',
          });
          if (appStore.userStore.project_id) {
            mitt.emit('getRegion');
            router.push({ name: 'insert' });
          } else {
            mitt.emit('getRegion');
            router.push({ name: 'Homepage' });
          }
          localStorage.removeItem('irData');
        }
      } catch (err) {
        creating.value = false;
        ElMessage.error('创建失败');
      }
    } else {
      ElMessage({
        message: '请检查参数',
        type: 'warning',
      });
    }
  });
};
const onReset = () => {
  irData.data = {
    domain_name: '',
    project_id: '',
    access_key: '',
    secret_access_key: '',
    region: '',
    user_id: '',
    keypair_name: '',
    agency_name: '',
    auxproxy_path: '',
    build_script_path: '',
    file_storage_region: '',
    docker_build_script_path: '',
  };
};
watch(
  () => irData.data,
  (newValue, oldValue) => {
    localStorage.setItem('irData', JSON.stringify(newValue));
  },
  { deep: true }
);
const backUserInfo = () => {
  router.go(-1);
};
onMounted(() => {
  getRegion();
  if (localStorage.getItem('irData')) {
    irData.data = JSON.parse(localStorage.getItem('irData') as string);
  }
});
if (localStorage.getItem('insertData')) {
  insertData.value = JSON.parse(localStorage.getItem('insertData') as string);
}
let newPwdReadOnly = ref(false);
let rePwdReadOnly = ref(false);
const newPwdFocus = (evt: any, isNew = true) => {
  if (evt) {
    evt.stopPropagation();
    evt.preventDefault();
  }
  setTimeout(() => {
    if (isNew) {
      newPwdReadOnly.value = false;
    } else {
      rePwdReadOnly.value = false;
    }
  }, 100);
};
watch(
  () => irData.data.access_key,
  function () {
    if (irData.data.access_key == '') {
      newPwdReadOnly.value = true;
      newPwdFocus(null);
    }
  }
);
watch(
  () => irData.data.secret_access_key,
  function () {
    if (irData.data.secret_access_key == '') {
      rePwdReadOnly.value = true;
      newPwdFocus(null, false);
    }
  }
);
const newPwdRef = ref();
const reNewPwdRef = ref();
const addClickEvt = () => {
  if (newPwdRef.value) {
    newPwdRef.value.input.onmousedown = () => {
      if (irData.data.access_key === '' || newPwdReadOnly.value) {
        newPwdRef.value.input.blur();

        setTimeout(() => {
          newPwdRef.value.input.focus();
        }, 0);
      }
      return false;
    };
  }
  if (reNewPwdRef.value) {
    reNewPwdRef.value.input.onmousedown = () => {
      if (irData.data.secret_access_key === '' || rePwdReadOnly.value) {
        reNewPwdRef.value.input.blur();
        setTimeout(() => {
          reNewPwdRef.value.input.focus();
        }, 0);
      }
      return false;
    };
  }
};
</script>
<template>
  <div id="createFleet">
    <div class="create-box">
      <span>为{{ insertData.name }}新建租户</span>
      <span
        class="back return"
        v-if="appStore.userStore.project_id"
        @click="backUserInfo"
        >&lt;&nbsp;返回</span
      >
    </div>
    <div class="form-box">
      <el-form
        ref="autoScalingRef"
        :model="irData.data"
        label-width="140px"
        label-position="left"
        :inline="true"
        :rules="rules"
        class="ac-form"
      >
        <div class="card-box">
          <div class="card-header">
            <div class="header-bar"></div>
            <div class="header-title">使用租户信息</div>
          </div>
          <div class="card-content">
            <el-form-item prop="domain_name">
              <template #label>
                <div class="item-label">租户名称</div>
              </template>
              <el-input
                v-model.trim="irData.data.domain_name"
                maxlength="1024"
              />
            </el-form-item>
            <el-form-item prop="project_id">
              <template #label>
                <div class="item-label">项目id</div>
              </template>
              <el-input
                v-model.trim="irData.data.project_id"
                maxlength="1024"
              />
            </el-form-item>
            <el-form-item prop="access_key">
              <template #label>
                <div class="item-label">AccessKey</div>
              </template>
              <el-input
                v-model.trim="irData.data.access_key"
                maxlength="1024"
                :type="
                  (newPwdReadOnly && irData.data.access_key) ||
                  irData.data.access_key
                    ? 'password'
                    : 'text'
                "
                autocomplete="new-password"
                :readonly="newPwdReadOnly"
                @click="addClickEvt"
                ref="newPwdRef"
                show-password
              />
            </el-form-item>
            <el-form-item prop="secret_access_key">
              <template #label>
                <div class="item-label">SecretAccessKey</div>
              </template>
              <el-input
                v-model.trim="irData.data.secret_access_key"
                maxlength="1024"
                :type="
                  (rePwdReadOnly && irData.data.secret_access_key) ||
                  irData.data.secret_access_key
                    ? 'password'
                    : 'text'
                "
                autocomplete="new-password"
                :readonly="rePwdReadOnly"
                @click="addClickEvt"
                ref="reNewPwdRef"
                show-password
              />
            </el-form-item>
            <el-form-item prop="region">
              <template #label>
                <div class="item-label">Region</div>
              </template>
              <el-select
                v-model="irData.data.region"
                placeholder="请选择region"
              >
                <el-option
                  v-for="item in regionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="keypair_name">
              <template #label>
                <div class="item-label">密钥名</div>
              </template>
              <el-input
                v-model.trim="irData.data.keypair_name"
                maxlength="1024"
              />
            </el-form-item>
            <el-form-item prop="agency_name">
              <template #label>
                <div class="item-label">云服务委托名</div>
              </template>
              <el-input
                v-model.trim="irData.data.agency_name"
                maxlength="1024"
              />
            </el-form-item>
          </div>
          <div class="card-header">
            <div class="header-bar"></div>
            <div class="header-title">应用包信息</div>
            <el-tooltip
              effect="dark"
              content="为空时使用后端环境变量"
              placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </div>
          <div class="card-content">
            <el-form-item prop="auxproxy_path">
              <template #label>
                <div class="item-label">AuxProxy路径</div>
              </template>
              <el-input
                v-model.trim="irData.data.auxproxy_path"
                maxlength="1024"
                placeholder="例：桶名/auxproxy.zip"
              />
            </el-form-item>
            <el-form-item prop="build_script_path">
              <template #label>
                <div class="item-label">ECS-应用包配置脚本路径</div>
              </template>
              <el-input
                v-model.trim="irData.data.build_script_path"
                maxlength="1024"
                placeholder="例：桶名/image_env.sh"
              />
            </el-form-item>

            <el-form-item prop="file_storage_region">
              <template #label>
                <div class="item-label">文件存放Region</div>
              </template>
              <el-select
                v-model="irData.data.file_storage_region"
                placeholder="请选择region"
              >
                <el-option
                  v-for="item in regionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="docker_build_script_path">
              <template #label>
                <div class="item-label">容器-应用包配置脚本路径</div>
              </template>
              <el-input
                v-model.trim="irData.data.docker_build_script_path"
                maxlength="1024"
                placeholder="例：桶名/docker_image_env.sh"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button
          class="btn new button"
          type="primary"
          @click="onSubmit(autoScalingRef)"
          >创建</el-button
        >
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
#createFleet {
  background-color: $blank-color;
  .create-box {
    height: 60px;
    width: calc(100% - 200px);
    position: absolute;
    top: 50px;
    left: 200px;
    background-color: $blank-color;
    color: $text-color;
    display: flex;
    align-items: center;
    z-index: 1;
    span {
      font-size: 16px;
      font-weight: bold;
      margin-left: 20px;
      margin-right: 10px;
      line-height: 60px;
    }
    .button {
      width: 100px;
      height: 28px;
    }
    .return {
      font-size: 14px;
      margin-left: 0px;
    }
  }
  .form-box {
    background-color: $blank-color;
    padding: 30px;
    margin-top: 60px;
    .select-box {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      .select-lable {
        width: 165px;
        color: $text-color;
        font-size: 14px;
        .must {
          color: rgb(245, 108, 108);
          margin-right: 4px;
        }
      }
    }

    .card-box {
      background-color: $blank-color;
      margin-bottom: 36px;
      .card-header {
        display: flex;
        align-items: center;
        height: 14px;
        margin-bottom: 44px;
        .el-icon {
          margin-left: 10px;
          color: #b4b6be;
        }
        .header-bar {
          height: 100%;
          width: 4px;
          background: $main-color;
          margin-right: 6px;
        }
        .header-title {
          height: 100%;
          line-height: 100%;
          color: #1d1d1f;
          font-weight: bold;
          font-size: 14px;
          margin-right: 10px;
        }
      }
    }
    .el-form-item {
      width: 50%;
      margin: 0;
      margin-bottom: 30px;

      :deep(.el-form-item__label) {
        width: 180px !important;
      }
      .item-label {
        width: 180px;
        color: $text-color;
      }

      .el-input {
        width: 480px;
        height: 30px;
      }
      .el-select {
        width: 480px;
        height: 30px;
        line-height: 30px;
        :deep(.el-input) {
          height: 30px;
          .el-input__inner {
            height: 30px;
          }
        }
      }
    }
  }
  .operateButton {
    justify-content: center;
    display: flex;
    gap: 20px;
    margin-top: 30px;
    .el-form-item {
      width: 260px;
    }
    .button {
      width: 120px;
      height: 34px;
    }
  }
}
</style>
